package TestThreadLocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author Mr.Wen
 * @Version 1.0
 */
public class Test2 {
    public static void main(String[] args) {
        ThreadLocalClass threadfield = new ThreadLocalClass();
        ExecutorService es = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            try {
                es.submit(() -> {
                    Integer integer = threadfield.threadfield.get();
                    threadfield.method();
                    System.out.println(Thread.currentThread().getName() + "号线程原本属性: " + integer + "\t修改后: " + threadfield.threadfield.get());
                });
            } finally {
                threadfield.threadfield.remove();/*对于每个线程,用完以后清空threadfield能够保证线程安全,防止线程溢出内存泄漏*/
            }
        }
        es.shutdown();
    }
}

class ThreadLocalClass {
    ThreadLocal<Integer> threadfield = new ThreadLocal<>().withInitial(() -> 0);

    public void method() {
        threadfield.set(threadfield.get() + 1);
    }
}
